package com.zyh.service.impl;

import com.zyh.core.BusinessException;
import com.zyh.dao.IUserDao;
import com.zyh.domain.User;
import com.zyh.service.IUserService;
import com.zyh.utils.MD5Utils;
import sun.security.provider.MD5;

import java.sql.SQLException;

public class UserServiceImpl implements IUserService {

    private final IUserDao userDao;

    public UserServiceImpl(IUserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public User login(String username, String password) throws SQLException {
        User target = this.userDao.getUserByUserName(username);
        if (target == null) {
            throw new BusinessException(500, "您输入的用户不存在！");
        }

        if (!target.getPassword().equals(MD5Utils.md5(MD5Utils.md5(password)))) {
            throw new BusinessException(500, "您输入的密码有误");
        }

        return target;
    }

    @Override
    public int register(User user) throws SQLException {
        User target = this.userDao.getUserByUserName(user.getUsername());
        if (target != null) {
            // 用户已经存在了，不能再添加了额
            throw new BusinessException(500, "用户名已经存在，请更换用户名！");
        }
        user.setPassword(MD5Utils.md5(MD5Utils.md5(user.getPassword())));
        return userDao.addUser(user);
    }
}
